package com.agile.leetcode.media;

import lombok.SneakyThrows;

import java.io.File;
import java.io.RandomAccessFile;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/5/17 22:09
 */
public class MediaTrunkPractice {
    public static void main(String[] args) {
       // trunk();
        merge();
    }

    /**
     * 文件的分块
     */
    @SneakyThrows
    public static void trunk() {
        // 地址
        String path = "D:\\czk\\1.mp3";
        // 创建文件
        File file = new File(path);
        // 创建随机文件
        RandomAccessFile raf_read = new RandomAccessFile(file, "r");
        // 拿到文件长度
        long length = file.length();
        // 分块数量
        long num = (long) Math.ceil(length * 1.0 / (1024 * 1024 * 1.0));
        if (num < 1) {
            num = 1;
        }
        // 创建阅读
        RandomAccessFile rad_write = null;
        //分块视频存储地址
        String trunkPath = "D:\\czk\\视频";
        int len = 0;
        byte[] b = new byte[1024];
        for (int i = 0; i < num; i++) {
            File file1=new File(trunkPath + "\\" + i + ".mp3");
            rad_write = new RandomAccessFile(file1, "rw");
            while ((len = raf_read.read(b)) != -1) {
                // 写
                rad_write.write(b, 0, len);
                // 是否有1m
                if (file1.length() > 1024 * 1024) break;
            }
        }
        // 关流
        rad_write.close();
        raf_read.close();
    }

    /**
     * 文件的合并
     */
    @SneakyThrows
    public static void merge() {
        //分块视频地址
        String trunkPath = "D:\\czk\\视频";
        //
        File file = new File(trunkPath);
        // w文件数量
        File[] files = file.listFiles();
        assert files != null;
        //
        int i = files.length;
        RandomAccessFile raf_read = null;
        // 写文件
        RandomAccessFile raf_write = new RandomAccessFile(new File("D:\\czk\\c.mp3"), "rw");
        byte[] bytes = new byte[1024];
        int len = 0;
        // 读取
        for (int j = 0; j < i; j++) {
            trunkPath = trunkPath + "\\" + j+".mp3";
            file = new File(trunkPath);
            // 创建读物
            raf_read = new RandomAccessFile(file, "r");
            while ((len = raf_read.read(bytes)) != -1) {
                // 写
                raf_write.write(bytes, 0, len);
            }
            // 重置
            trunkPath = "D:\\czk\\视频";
        }
        assert raf_read != null;
        raf_read.close();
        raf_write.close();
    }
}
